/* Copyright 2009 CtrlSpace Platform
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Contributor(s):
 * 	Marc Obaldo (marcklaser@gmail.com)
 */

dojo.provide("ctrlspace.ui.tree.ProjectTree");
dojo.declare("ctrlspace.ui.tree.ProjectTree", dijit.Tree, {
	postCreate: function(/* Object*/ args) {
		this.storeObject = new dojo.data.ItemFileReadStore({
	        url: "p/Projects?command=get_all&" + djConfig.cacheBust,
	        clearOnClose: true,
	        urlPreventCache: true
	    });
	
	    var forestModel = new dijit.tree.ForestStoreModel({
	        store: this.storeObject,
	        rootId: "myProjects",
	        rootLabel: "My Projects",
	        childrenAttrs: ["children"]
	    });
	    
	    this.showRoot = false;
	    this.model = forestModel;
	    this.inherited(arguments);
	    this.openOnDblClick = true;
	    this.uiLoading();
	},
	
	onDblClick: function(targetItem, node, event) {
		dojo.stopEvent(event);
		// Opened file
		var type = targetItem['type'][0]['type'][0];
		if (type != "emptyPackage" && type != "package" && type != "folder") {
			IDE.getUI().getEditors().openEditor(targetItem["projectId"][0], targetItem["path"][0],
					targetItem["label"][0], targetItem["iconClass"][0]);
		}
	},
	
	onLoad: function() {
		this.inherited(arguments);
		this.uiLoaded();
	},

    getIconClass: function(/*dojo.data.Item*/ item, /*Boolean*/ opened){
		return item.iconClass;
	},

	refresh : function() {
		this.uiLoading();
		// Get root and collapse
		this._itemNodesMap = {};  
		this._collapseNode(this.rootNode);
        
        // Reload from model
        this.rootNode.state = 'UNCHECKED';
        this.model.root.children = null;
		this.model.store.close();
		this.model.store.fetch();
		
		// Expand and update display
		this._expandNode(this.rootNode);
		this.uiLoaded();
	},
	
	uiLoading: function() {
		if (this.domNode) {
			dojo.addClass(this.domNode, 'csLoading');
		}
	},
	
	uiLoaded: function() {
		if (this.domNode) {
			dojo.removeClass(this.domNode, 'csLoading');
		}
	}
});